package br.com.gestaofacil.autenticacao.core.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
public class User implements Serializable, UserDetails {

  private static final long serialVersionUID = -8451679170281063697L;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  
  @NotNull
  @Size(min = 5, max = 20)
  @Column(unique = true)
  private String username;

  @NotNull
  @Size(min = 5, max = 10)
  private String password;

  @ManyToMany(fetch = FetchType.EAGER)
  private List<Role> roles;
  
  @Transient
  public Collection<GrantedAuthority> getAuthorities() {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    for (Role role : roles) {
      result.add(new GrantedAuthorityImpl(role.getName()));
    }
    return result;
  }
  
  @Transient
  public boolean isEnabled() {
    return true;
  }

  @Transient
  public boolean isAccountNonExpired() {
    return true;
  }

  @Transient
  public boolean isAccountNonLocked() {
    return true;
  }

  @Transient
  public boolean isCredentialsNonExpired() {
    return true;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public List<Role> getRoles() {
    return roles;
  }

  public void setRoles(List<Role> roles) {
    this.roles = roles;
  }
  
}
